﻿#region 文件信息

/*----------------------------------------------------------------
//
// 文件名称：
// 文件功能描述：
// 设计要求：
//
// 文 件 名：    SysUserManagerViewModel
// 创建者：      杨程
// 创建日期：	    2023/1/30 12:45:58

//----------------------------------------------------------------*/

#endregion

using Vampirewal.Core.GeneralTree;
using Vampirewal.Core.WindoSetting;

namespace Vampirewal.Admin.Client.ViewModels.ViewModel.SysManager;

/// <summary>
/// 客户端用户管理-管理员可用
/// </summary>
[VampirewalIoCRegister(ClientViewModelKeys.SysUserManagerViewModel)]
public partial class SysUserManagerViewModel : BillListBaseVM<Sys_UserVO, Sys_UserVO>
{
    private IRpcService RpcService { get; set; }

    /// <summary>
    ///
    /// </summary>
    public SysUserManagerViewModel(IVampirewalCoreDialogMessage dialog, IRpcService rpcService) : base()
    {
        Dialog = dialog;
        RpcService = rpcService;
        //构造函数

        rpcService.CallApi<List<Sys_OrgDTO>>(RpcMethod.GetAllOrg, InvokeOptionUtil.Fast_WaitInvoke_10s, (response) =>
        {
            var Sys_OrgVOs = response.Select(s => s.SimpleMap<Sys_OrgVO>());
            OrgList.LoadFullNodes(Sys_OrgVOs);

            SelectedOrg = response.Find(f => f.BillId == VampirewalCoreContext.GetInstance().GetContext<string>("OrgId")).SimpleMap<Sys_OrgVO>();
        },
        (ex) =>
        {
            //Dialog.ShowPopupWindow(ex.Message, WindowsManager.GetInstance().MainWindow, MessageType.Error);
            Dialog.ShowPopupWindow(new Core.WindoSetting.PopupWindowSetting()
            {
                Message = ex.Message,
                OwnerWindow = WindowsManager.GetInstance().MainWindow,
                Type = Core.WindoSetting.MessageType.Error
            });
        });

        BindData(Request);

        TreeListViewActionsCommand = new IVampirewalCoreEventCommand[]
        {
            new VampirewalCoreEventCommand("SelectedItemChanged","SelectedItem", new RelayCommand<GeneralTreeContainer<Sys_OrgVO>>((Selected) =>
            {
                var org = Selected.TreeNode;

                if (org.OrgType != 0)
                {
                    Request.OrgId = org.BillId;
                    SelectedOrg = org;
                    BindData(Request);
                }
            }))
        };
    }

    #region [     重写     ]

    protected override void InitVM()
    {
        OrgList = new TreeBuilderByFullLoad<Sys_OrgVO>();
        Request = new UserRequest() { Limit = this.Limit, Page = this.Page };
    }

    private string ViewKey { get; set; }

    protected override IUcViewBase SetView()
    {
        switch (ViewKey)
        {
            case ClientViewKeys.EditSysUserView:
                return WindowsManager.GetInstance().GetView(ViewKey);

            default:
                throw new NotImplementedException();
        }
    }

    protected void GetList()
    {
        EntityList.Clear();

        RpcService.CallApi<PageContainer<Sys_UserDTO>>(RpcMethod.GetPageListUser, InvokeOptionUtil.Fast_WaitInvoke_30s, (response) =>
        {
            EntityList.Clear();

            PageCount = response.PageCount;
            TotalCount = response.TotalCount;

            foreach (var item in response.Data)
            {
                EntityList.Add(item.SimpleMap<Sys_UserVO>());
            }
        },
        (ex) =>
        {
            //Dialog.ShowPopupWindow(ex.Message, WindowsManager.GetInstance().MainWindow, MessageType.Error);
            Dialog.ShowPopupWindow(new Core.WindoSetting.PopupWindowSetting()
            {
                Message = ex.Message,
                OwnerWindow = WindowsManager.GetInstance().MainWindow,
                Type = Core.WindoSetting.MessageType.Error
            });
        }, new UserRequest() { Limit = this.Limit, Page = this.Page });
    }

    public override void ExecuteBeforeCloseDialogWindow(object obj)
    {
        GetList();
    }

    #endregion

    #region [     属性     ]

    /// <summary>
    /// 底部页面
    /// </summary>
    [ObservableProperty]
    public IUcViewBase bottomContext;

    public TreeBuilderByFullLoad<Sys_OrgVO> OrgList { get; set; }

    public IVampirewalCoreEventCommand[] TreeListViewActionsCommand { get; set; }

    private UserRequest Request { get; set; }

    private Sys_OrgVO SelectedOrg { get; set; }

    #endregion

    #region [     私有方法     ]

    //private void TreeListViewSelectedItemChanged(object sender, RoutedPropertyChangedEventArgs<object> e)
    //{
    //    var Trees = sender as TreeListView;

    //    if (Trees.SelectedItem is GeneralTreeContainer<Sys_OrgVO> Selected)
    //    {
    //        var org = Selected.TreeNode;

    //        if (org.OrgType != 0)
    //        {
    //            Request.OrgId = org.BillId;
    //            SelectedOrg = org;
    //            BindData(Request);
    //        }
    //    }
    //}

    private void BindData(UserRequest request)
    {
        EntityList.Clear();

        RpcService.CallApi<PageContainer<Sys_UserDTO>>(RpcMethod.GetPageListUser, InvokeOptionUtil.Fast_WaitInvoke_10s, (response) =>
        {
            PageCount = response.PageCount;
            TotalCount = response.TotalCount;

            foreach (var item in response.Data)
            {
                EntityList.Add(item.SimpleMap<Sys_UserVO>());
            }
        },
        (ex) =>
        {
            //Dialog.ShowPopupWindow(ex.Message, WindowsManager.GetInstance().MainWindow, MessageType.Error);
            Dialog.ShowPopupWindow(new Core.WindoSetting.PopupWindowSetting()
            {
                Message = ex.Message,
                OwnerWindow = WindowsManager.GetInstance().MainWindow,
                Type = Core.WindoSetting.MessageType.Error
            });
        },
        //new UserRequest() { Limit = this.Limit, Page = this.Page }
        request
        );
    }

    #endregion

    #region [     Command命令     ]

    #region [     分页命令     ]

    ///// <summary>
    /////     页码改变命令
    ///// </summary>
    //public RelayCommand<FunctionEventArgs<int>> PageUpdatedCmd =>
    //    new Lazy<RelayCommand<FunctionEventArgs<int>>>(() =>
    //        new RelayCommand<FunctionEventArgs<int>>(PageUpdated)).Value;

    ///// <summary>
    /////     页码改变
    ///// </summary>
    //private void PageUpdated(FunctionEventArgs<int>? info)
    //{
    //    if (info == null)
    //    {
    //        return;
    //    }

    //    EntityList.Clear();

    //    Page = info.Info;
    //    Request.Page = info.Info;
    //    BindData(Request);
    //}

    #endregion

    /// <summary>
    /// 添加新用户命令
    /// </summary>
    [RelayCommand]
    public void AddNewUser()
    {
        ViewKey = ClientViewKeys.EditSysUserView;

        List<SimplePassData> data = new List<SimplePassData>()
        {
            new SimplePassData() { Key = "SelectedOrg", Value = SelectedOrg }
        };

        SetDialogWindowSetting(new DialogWindowSetting()
        {
            WindowWidth = 800,
            WindowHeight = 600,
            IsShowMaxButton = false,
            IsShowMinButton = false,
            IsOpenWindowSize = false,
            TitleFontSize = 15,
            CloseDialogWindowCallBackCommand = new RelayCommand<object>(ExecuteBeforeCloseDialogWindow),
            IconStr = "pack://application:,,,/Vampirewal.Admin.Client;component/Logo.png"
        });

        ExecuteShowDialogWindow(data);
    }

    /// <summary>
    /// 查看用户详细信息命令
    /// </summary>
    /// <param name="vo"></param>
    [RelayCommand]
    public void LookUserInfo(Sys_UserVO vo)
    {
        BottomContext = WindowsManager.GetInstance().GetView(ClientViewKeys.EditSysUserView, Param: vo);
    }

    #endregion
}

/// <summary>
/// 系统用户编辑新增页VM
/// </summary>
[VampirewalIoCRegister(ClientViewModelKeys.EditSysUserViewModel)]
public partial class EditSysUserViewModel : BillVM<Sys_UserVO>
{
    private IVampirewalCoreDialogMessage Dialog { get; set; }
    private IRpcService RpcService { get; set; }

    private Sys_OrgVO SelectedOrg { get; set; }

    public List<EnumberCreditType> GenderEnum { get; set; }
    public List<EnumberCreditType> UserStateEnum { get; set; }

    public ObservableCollection<Sys_RoleTemplateVO> Roles { get; set; }

    public EditSysUserViewModel(IVampirewalCoreDialogMessage dialog, IRpcService rpcService) : base()
    {
        Dialog = dialog;
        RpcService = rpcService;

        var DicCategorys = VampirewalCoreContext.GetInstance().GetContext<List<Sys_DicCategoryVO>>("DicCategory");

        #region 获取性别枚举值

        var GenderCategory = DicCategorys.First(f => f.DicCategoryName.Equals("性别"));

        rpcService.CallApi<List<EnumberCreditType>>(RpcMethod.GetDicEnumberCreditListByCategoryId, InvokeOptionUtil.Fast_WaitInvoke_10s, (response) =>
        {
            //1、
            GenderEnum = response.OrderBy(o => o.Classification).ToList();
            //2、
            //GenderEnum=response.Where(e => e.Classification >= 1 && e.Classification <= 2).OrderBy(o => o.Classification).ToList();
        }, (ex) =>
        {
            //Dialog.ShowPopupWindow(ex.Message, WindowsManager.GetInstance().GetDialogWindow(ViewId), MessageType.Error);
            Dialog.ShowPopupWindow(new Core.WindoSetting.PopupWindowSetting()
            {
                Message = ex.Message,
                OwnerWindow = WindowsManager.GetInstance().MainWindow,
                Type = Core.WindoSetting.MessageType.Error
            });
        }, GenderCategory.BillId);

        #endregion

        #region 获取启用状态枚举值

        var UserStateCategory = DicCategorys.First(f => f.DicCategoryName.Equals("用户是否启用"));

        rpcService.CallApi<List<EnumberCreditType>>(RpcMethod.GetDicEnumberCreditListByCategoryId, InvokeOptionUtil.Fast_WaitInvoke_10s, (response) =>
        {
            //1、
            UserStateEnum = response.OrderBy(o => o.Classification).ToList();
            //2、
            //UserStateEnum=response.Where(e => e.Classification >= 1 && e.Classification <= 2).OrderBy(o => o.Classification).ToList();
        }, (ex) =>
        {
            //Dialog.ShowPopupWindow(ex.Message, WindowsManager.GetInstance().GetDialogWindow(ViewId), MessageType.Error);
            Dialog.ShowPopupWindow(new Core.WindoSetting.PopupWindowSetting()
            {
                Message = ex.Message,
                OwnerWindow = WindowsManager.GetInstance().MainWindow,
                Type = Core.WindoSetting.MessageType.Error
            });
        }, UserStateCategory.BillId);

        #endregion

        #region 获取当前租户下的所有角色

        rpcService.CallApi<List<Sys_RoleTemplateDTO>>(RpcMethod.QueryRoleTemplate, InvokeOptionUtil.Fast_WaitInvoke_10s, response =>
        {
            foreach (var role in response)
            {
                Roles.Add(role.SimpleMap<Sys_RoleTemplateVO>());
            }
        }, ex =>
        {
            //Dialog.ShowPopupWindow(ex.Message, WindowsManager.GetInstance().GetDialogWindow(ViewId), MessageType.Error);
            Dialog.ShowPopupWindow(new Core.WindoSetting.PopupWindowSetting()
            {
                Message = ex.Message,
                OwnerWindow = WindowsManager.GetInstance().MainWindow,
                Type = Core.WindoSetting.MessageType.Error
            });
        });

        #endregion
    }

    private bool IsNew = false;

    public override void InitData()
    {
        GenderEnum = new List<EnumberCreditType>();
        Roles = new ObservableCollection<Sys_RoleTemplateVO>();
    }

    public override void PassData(object obj)
    {
        var model = obj as Sys_UserVO;

        if (model != null)
        {
            Title = $"编辑 <{model.Name}> 信息";
            SetEntity(model);
            IsNew = false;
        }
        else
        {
            Title = $"新增用户";

            var data = obj as List<SimplePassData>;

            foreach (var item in data)
            {
                switch (item.Key)
                {
                    case "SelectedOrg":
                        {
                            SelectedOrg = (Sys_OrgVO)item.Value;
                        }
                        break;
                }
            }

            if (SelectedOrg == null)
            {
                CloseView();
            }

            IsNew = true;
        }
    }

    protected override void CloseView()
    {
        WindowsManager.GetInstance().CloseDialogWindow(ViewId);
    }

    /// <summary>
    /// 保存用户命令
    /// </summary>
    [RelayCommand]
    public void SaveUser()
    {
        RpcService.CallApi<Sys_UserDTO>(RpcMethod.GetCurrentDeptLeaderByOrgId, InvokeOptionUtil.Fast_WaitInvoke_10s, response =>
        {
            if (response != null)
            {
                //Dialog.ShowPopupWindow($"当前部门已存在一位负责人，请先取消{response.Name}的负责人身份再操作！", WindowsManager.GetInstance().GetDialogWindow(ViewId), MessageType.Error);
                Dialog.ShowPopupWindow(new Core.WindoSetting.PopupWindowSetting()
                {
                    Message = $"当前部门已存在一位负责人，请先取消{response.Name}的负责人身份再操作！",
                    OwnerWindow = WindowsManager.GetInstance().GetDialogWindow(ViewId),
                    Type = Core.WindoSetting.MessageType.Error
                });
                return;
            }
        }, ex =>
        {
        }, IsNew ? SelectedOrg.BillId : Entity.OrgId);

        if (IsNew)
        {
            Entity.OrgId = SelectedOrg.BillId;
            Entity.OrgName = SelectedOrg.OrgName;
            Entity.TenantId = SelectedOrg.TenantId;
            Entity.DepartmentId = SelectedOrg.BillId;
            Entity.DirectLeaderId = "";

            RpcService.CallApi<bool>(RpcMethod.CreateUser, InvokeOptionUtil.Fast_WaitInvoke_10s, (response) =>
            {
                CloseView();
            }, ex =>
            {
                //Dialog.ShowPopupWindow($"新增用户失败！\r\n{ex.Message}", WindowsManager.GetInstance().GetDialogWindow(ViewId), MessageType.Error);
                Dialog.ShowPopupWindow(new Core.WindoSetting.PopupWindowSetting()
                {
                    Message = $"新增用户失败！\r\n{ex.Message}",
                    OwnerWindow = WindowsManager.GetInstance().GetDialogWindow(ViewId),
                    Type = Core.WindoSetting.MessageType.Error
                });
            }, Entity.SimpleMap<Sys_UserDTO>());
        }
        else
        {
            RpcService.CallApi<bool>(RpcMethod.UpdateUser, InvokeOptionUtil.Fast_WaitInvoke_10s, (response) =>
            {
                //Dialog.ShowPopupWindow("保存成功！", WindowsManager.GetInstance().MainWindow, MessageType.Successful);
                Dialog.ShowPopupWindow(new Core.WindoSetting.PopupWindowSetting()
                {
                    Message = "保存成功！",
                    OwnerWindow = WindowsManager.GetInstance().MainWindow,
                    Type = Core.WindoSetting.MessageType.Successful
                });
            }, ex =>
            {
                //Dialog.ShowPopupWindow($"保存失败！\r\n{ex.Message}", WindowsManager.GetInstance().MainWindow, MessageType.Error);
                Dialog.ShowPopupWindow(new Core.WindoSetting.PopupWindowSetting()
                {
                    Message = $"保存失败！\r\n{ex.Message}",
                    OwnerWindow = WindowsManager.GetInstance().MainWindow,
                    Type = Core.WindoSetting.MessageType.Error
                });
            }, Entity.SimpleMap<Sys_UserDTO>());
        }
    }
}